#include "stm32f10x.h"                  // Device header
#include "PWM.h"

void PWM_Init(TIM_TypeDef* TIMx)
{
	//1. RCC开启时钟，把要用的TIM外设和GPIO外设的时钟打开
	//2.配置时基单元，包括时钟源选择，预分频器，自动重装载器，时基单元就配置好了
	//3.配置输出比较单元，包括CCR的值，输出比较模式，极性选择，输出使能这些参数
	//4.初始化GPIO，把PWM的OC输出GPIO引脚配置为复用输出模式
	//5.运行控制，启动计数器
	
	//Setp 1.
	//RCC APB1的外设时钟控制，因为TIM2在STM32的APB1外设总线上
	if(TIMx == TIM3)
		RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
	if(TIMx == TIM2)
		RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
	
	//GPIO初始化
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
	GPIO_InitTypeDef GPIO_InitStruct;
	GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF_PP;	//复用推挽输出
	GPIO_InitStruct.GPIO_Pin = GPIO_Pin_6;
	GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOA, &GPIO_InitStruct);
	
	GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF_PP;	//复用推挽输出
	GPIO_InitStruct.GPIO_Pin = GPIO_Pin_0;
	GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOA, &GPIO_InitStruct);
	
	
	//AFIO
//	RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);
//	GPIO_PinRemapConfig(GPIO_PartialRemap1_TIM2, ENABLE);
//	GPIO_PinRemapConfig(GPIO_Remap_SWJ_JTAGDisable, ENABLE);
	
	
	//Setp 2.
	//选择时基单元的时钟，使用内部RCC时钟 CLK_INT (Clock_Internal)
	TIM_InternalClockConfig(TIMx);
	
	//Setp 3.
	//配置时基单元
	TIM_TimeBaseInitTypeDef TimeBaseInitStruct;
	TimeBaseInitStruct.TIM_ClockDivision = TIM_CKD_DIV1;		//时钟信号滤波使用，滤波的采样频率，采样点数
	TimeBaseInitStruct.TIM_CounterMode = TIM_CounterMode_Up;	//计数器向上计数
	TimeBaseInitStruct.TIM_Period = 100 - 1;					//ARR, Auto-Reload Register 自动重装载寄存器的值，记得需要减一
	TimeBaseInitStruct.TIM_Prescaler = 72 - 1;					//PSC, 预分频器的值，记得需要减一
	TimeBaseInitStruct.TIM_RepetitionCounter = 0;				//重复计数器的值	
	TIM_TimeBaseInit(TIMx, &TimeBaseInitStruct);
	
	//输出表通道1
	TIM_OCInitTypeDef TIM_OCInitStruct;
	TIM_OCStructInit(&TIM_OCInitStruct);
	TIM_OCInitStruct.TIM_OCMode = TIM_OCMode_PWM1;
	TIM_OCInitStruct.TIM_OCPolarity = TIM_OCPolarity_High;
	TIM_OCInitStruct.TIM_OutputState = TIM_OutputState_Enable;
	TIM_OCInitStruct.TIM_Pulse = 10;		//CCR
	TIM_OC1Init(TIMx, &TIM_OCInitStruct);
	
	
	//输出PWM目标，PWM频率1KHz，PWM占空比 50%，PWM分辨率 1%
	//PWM频率=72MHz/(PSC+1)(ARR+1) =>PSC 720
	//PWM占空比=CCR/(ARR+1) ==>CRR 50
	//PWM分辨率=1/(ARR+1)  ==>ARR 100
	//
	
	//Setp 6.
	//定时器启动
	//TIM_Cmd(TIMx, ENABLE);
	
}

void PWM_SetCompare1(TIM_TypeDef* TIMx, uint16_t Compare)
{
	TIM_SetCompare1(TIMx, Compare);
}
